package com.yunsom.testdemo.threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Xbao
 * @description
 * @date 2022/6/1 17:35
 */
public class ThreadLocalTest {
  private static final ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();
  public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    // 提交5个任务,使用5个线程
    for(int i=0;i<5;i++){
      executorService.execute(new Runnable() {
        @Override
        public void run() {
          // 获取threadLocal中当前线程绑定的值
          if(threadLocal.get()==null){
            // 设置threadLocal中当前线程绑定的值
            threadLocal.set(new Person());
          }
          System.out.println("初始的本地值："+threadLocal.get());
          // 每个线程执行10次
          for(int i=0;i<10;i++){
            Person foo = threadLocal.get();
            foo.setAge(foo.getAge()+1);
            // 睡眠1s
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          System.out.println("累加10次之后的本地值："+threadLocal.get());
          // 删除threadLocal中当前线程所绑定的值，这点对于线程池中的线程特别重要
          threadLocal.remove();
        }
      });
    }
  }


}

